define(['dojo/_base/declare', 'dojo/_base/array', 'dojo/_base/lang', 'dijit/_Widget',
	'dojo/dom-construct', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin',
	'dojo/text!feedEditor/Main.html', 'dojo/request/xhr', 'feedEditor/widget/MovieItem',
	'dijit/layout/BorderContainer', 'dijit/layout/ContentPane', 'dijit/form/TextBox',
	'dijit/form/Button'],
	function(declare, array, lang, _Widget, domConstruct, _TemplatedMixin, _WidgetsInTemplateMixin,
		template, xhr, MovieItem) {
		return declare('feedEditor.Main', [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
			templateString: template,
			_borderContainer: null,
			_movieList: null,
			_movieTextBox: null,

			postCreate: function() {
				this.inherited(arguments);
				this._getMovies();
			},

			_getMovies: function() {
				this._movieTextBox.set('value', '');
				xhr('/tt-rss-feed-editor/FeedEditor', {
					method: 'GET',
					handleAs: 'json',
					sync: true
				}).then(lang.hitch(this, this.parseData));
			},

			_sortResponses: function(responses) {
				responses.sort(function(a, b) {
					if (a.id > b.id) {
						return -1;
					} else {
						return 1
					}
				});
			},

			parseData: function(responses) {
				var movieDomNode = this._movieList.domNode;
				domConstruct.empty(movieDomNode);
				var list = domConstruct.create('ul', null, movieDomNode);

				this._sortResponses(responses);

				array.forEach(responses, lang.hitch(this, function(response) {
					this._addMovieToList(response, list);
				}));
			},

			_addMovieToList: function(json, list) {
				var title = json.title;
				if (title === 'Movies' || title === 'New TV Shows') {
					return;
				}

				var movieItem = new MovieItem(null, null, json.id, title, this);
				list.appendChild(movieItem.domNode);
			},

			_onAddMovieClick: function() {
				xhr('/tt-rss-feed-editor/FeedEditor', {
					method: 'POST',
					data: {
						'type': 'add',
						'title': this._movieTextBox.get('value')
					},
					sync: true
				}).then(lang.hitch(this, this._getMovies), lang.hitch(this, this._onError));
			},

			_onError: function(err) {
				var err = err;
			}
		});
	});
